#region File Header
//----------------------------------------------------------------
// Copyright (C) 2002 Stefan Kyntchev
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
#endregion File Header

using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
using System.Threading;
using AirWeb.Support.Diagnostics;
using System.Xml;


namespace AirWeb.ApplicationTools.Common
{
	/// <summary>
	/// Summary description for CommonHelper.
	/// </summary>
	public class CommonHelper
	{
		public static Hashtable ParseLogEntry(string i_map)
		{
			Hashtable h = new Hashtable();

			// Get the host name
			int hi = i_map.IndexOf("Host: ");
			int ui = i_map.IndexOf(". User: ");
			int fi = i_map.IndexOf(". Home page hit from: ");

			if(hi != -1)
			{
				hi+=6;
				if(ui != -1)
				{
					h.Add("Host",i_map.Substring(hi,ui-hi));
				}
			}

			// Get the user
			if(ui != -1)
			{
				ui+=8;
			
				if(fi != -1)
				{
					h.Add("User",i_map.Substring(ui,fi-ui));
				}
			}

			// Get the from address
			if(fi != -1)
			{
				fi+=22;
				h.Add("From",i_map.Substring(fi));
			}

			return h;
		}


		/// <summary>
		/// Verifies if the supplid file is a move file. This is done by cheking the file extension
		/// </summary>
		/// <param name="i_file">The name of the file</param>
		/// <returns>true if the file is a movie file</returns>
		public static bool IsMovie(string i_file)
		{
			string [] movies = { ".mov",".wmv",".mpg",".avi" };

			i_file = i_file.ToLower();
			foreach(string s in movies)
			{
				if(i_file.IndexOf(s) != -1)
					return true;
			}
			
			return false;
		}

		/// <summary>
		/// Logs a nicely formatted exception to the application log
		/// </summary>
		/// <param name="i_e">The exception to log</param>
		public static void LogException(Exception i_e)
		{
			if(i_e != null)
				ApplicationLog.WriteError(ApplicationLog.FormatException(i_e,"Exception occured!"));
		}

		/// <summary>
		/// Logs an entry in the application log for a user login. Because the obtaining of the information
		/// about the user can take some time - creates a separate thread to to the logging
		/// </summary>
		/// <param name="i_userName">The name of the user</param>
		/// <param name="i_userIP">The IP address from which the login was made</param>
		public static void LogUserLogin(string i_userName, string i_userIP)
		{
			LoginLogger l = new LoginLogger(i_userName,i_userIP);
			WaitCallback wcb = new WaitCallback(l.Log);
			ThreadPool.QueueUserWorkItem(wcb);
		}

		/// <summary>
		/// This class is responsible for formatting of an entry in the log file for every
		/// user login. The entry contains the user name of the user and information about 
		/// the location (IP and geographical) from where the login was made. To obtain
		/// the geographical location we will use a free WebService
		/// </summary>
		public class LoginLogger
		{
			string m_un;
			string m_uip;

			/// <summary>
			/// Constructor
			/// </summary>
			/// <param name="i_username">The user name of the user</param>
			/// <param name="i_userIP">The IP address machine that the request</param>
			public LoginLogger(string i_username, string i_userIP)
			{
				m_un = i_username;
				m_uip = i_userIP;
			}

			/// <summary>
			/// Formats the log entry string
			/// </summary>
			/// <param name="i_map">Map of various information retrieved about the user</param>
			/// <returns></returns>
			string CreateLogEntry(string i_host, string i_user, string i_location)
			{
				return "Host: " + i_host + ". User: " + i_user + ". Home page hit from: " + i_location;
			}

			/// <summary>
			/// Gets the geographical location of a user given ip address
			/// </summary>
			/// <param name="i_ipAddress">The ip address to perform the location lookup</param>
			/// <returns>Formated string of the location or empty string if no translation was possible</returns>
			string GetLocation(string i_ipAddress)
			{
				return "";
			}

			/// <summary>
			/// This method actualiy does the logging itself
			/// </summary>
			public void Log(object i_state)
			{
				string requester = "";
				string reqaddr = "";
				try
				{
					// Try to translate the IP to Domain name
					IPHostEntry hostInfo  = Dns.GetHostByAddress(m_uip);
					requester = "(" + m_uip + ") " + hostInfo.HostName;

					//Try to get the location
					reqaddr = GetLocation(m_uip);
				}
				catch
				{
					requester = m_uip + " (Unable to perform DNS lookup)";
				}

				NameValueCollection config = (NameValueCollection)
					ConfigurationSettings.GetConfig("flashBack/directories");		
	
				ApplicationLog.WriteInfo(CreateLogEntry(config["HOSTED_FOR"],m_un,requester + reqaddr));
			}
		}
	}
}
